# coding=utf-8

"""
    Created by Kalyter on 2018-02-17.
"""

from learning.scientifc import writer
from learning.scientifc.jobs.job import Job
from learning.scientifc.readers.reader import ReaderFactory


class SumJob(Job):
    name = '求和作业'

    def __init__(self, app):
        super().__init__(app)
        self.source_file = self.app.config.get('SUM_SOURCE_FILE')
        self.factory = ReaderFactory(self.app)

    def run(self, *args, **kwargs):
        # 第一步，准备工作
        reader = self.factory.create(self.source_file)
        data = {}
        protocol_data = {}
        protocols = []
        header = reader.row_values(0)
        custom_header = (
            'Year',
            'Month',
            'Hscode',
            '申报金额',
            '减免关税额',
            '协定代码'
        )

        write_header = (
            'Year',
            'Month',
            'Hscode',
            'total'
        )

        year_index = header.index(custom_header[0])
        month_index = header.index(custom_header[1])
        hs_index = header.index(custom_header[2])
        apply_index = header.index(custom_header[3])
        reduce_index = header.index(custom_header[4])
        protocol_index = header.index(custom_header[5])

        # 第二步，收集数据
        for i, row in reader.range(1):
            key = (
                str(int(row[year_index])),
                str(int(row[month_index])),
                str(row[hs_index])[:8]
                )
            try:
                protocol = str(int(row[protocol_index]))
            except ValueError:
                protocol = '无'

            if protocol not in protocols:
                protocols.append(protocol)
            protocol_key = key + (protocol,)
            item = data.setdefault(key, [0.])
            protocol_item = protocol_data.setdefault(protocol_key, [0.])
            try:
                apply_float = float(row[apply_index])
            except:
                apply_float = 0.

            # try:
            #     reduce_float = float(row[reduce_index])
            # except:
            #     reduce_float = 0.
            item[0] += apply_float
            protocol_item[0] += apply_float
            # item[1] += reduce_float

        # 第三步，转化数据，为输出数据做准备
        # write_data = [tuple(custom_header)]
        #
        # for key, value in data.items():
        #     write_data.append(key + (value[0], value[1]))

        write_data = []
        write_header += tuple(map(lambda x: 'usage_value(协定代码=%s)' % x, protocols))

        write_data.append(write_header)

        for key, value in data.items():
            values = [value[0]] + [0] * len(protocols)
            for i, p in enumerate(protocols):
                for p_key, p_value in protocol_data.items():
                    if p_key[:len(key)] == key and p_key[-1] == p:
                        values[i + 1] = p_value[0]

            write_values = []
            for v in values:
                try:
                    write_values.append('%.2f' % v)
                except:
                    write_values.append(v)

            write_data.append(key + tuple(write_values))

        writer.write(write_data)
